<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import * as apiUtil from '@/api/ApiUtils'
import {Resource} from "@/api/AuthResourceApi"
import * as api from '@/api/AuthResourceApi'
import * as apiapi from '@/api/AuthApiApi'
import { notification } from 'ant-design-vue'
import IconSelector from '@/components/IconSelector.vue'


const props = defineProps<{
  dataId?: number
  type?: string
  menuId?: number
}>();

// Emits 定义
const emit = defineEmits<{
  (e: 'close'): void
  (e: 'successed'): void
}>()



const formData = ref<Resource>(new Resource());

// 验证规则
const rules = {
  name: [{ required: true, message: '名称必填!' }],
  webPath: [{ required: true, message: '前端路径必填!' }],
  groupId: [{ required: true, message: '分组必选!' }],
}

// 其他响应式状态
const groupTree = ref<any[]>([])
const apiOptions = ref<any[]>([])

// 计算属性：操作类型
const actionType = () => (props.dataId ? '修改' : '添加')

// 方法定义
const onFinish = (values: any) => {
  console.log('Success:', values, props.dataId)
  handleSave()
}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo)
}

const handleClose = () => {
  emit('close')
}

const handleSuccessed = () => {
  emit('successed')
}

const handleIconChanged = (name: string) => {
  formData.value.iconName = name
}

const handleSave = () => {
  if (formData.value.apiList && formData.value.apiList.length > 0) {
    formData.value.apiSignatureCode = formData.value.apiList.join(',')
  }
  api.save(formData.value).then((res) => {
    if (apiUtil.isSuccessed(res)) {
      handleSuccessed()
      handleClose()
      notification.success({
        message: `${actionType()}成功`,
        description: `${actionType()}成功`,
      })
    } else {
      notification.error({
        message: '提交失败',
        description: res.message,
      })
    }
  })
}

const handleGetDetail = () => {
  if (!props.dataId) return
  api.getById(props.dataId).then((res) => {
    if (apiUtil.isSuccessed(res)) {
      formData.value = res.data
      if (res.data.apiSignatureCode) {
        formData.value.apiList = res.data.apiSignatureCode.split(',')
      }
    }
  })
}

// Watch 监听 dataId 变化
watch(
    () => props.dataId,
    (newValue) => {
      console.log('dataId:', newValue)
      if (newValue) {
        handleGetDetail()
      } else {
        formData.value = new Resource();
      }
    }
)

// 生命周期 mounted
onMounted(() => {
  if (props.dataId) {
    handleGetDetail()
  }
  if (props.menuId) {
    formData.value.parentId = props.menuId
  }
  formData.value.type = props.type || 'Menu'

  // 获取分组选项
  api.menuGroupList().then((res) => {
    if (apiUtil.isSuccessed(res)) {
      if(res.data){
        for (let item of res.data) {
          item.label = item.name;
          item.value = item.id;
        }
        groupTree.value = res.data;
      }
    }
  })

  // 查询 API 分组选项
  apiapi.getGroupOptions().then((res) => {
    if (apiUtil.isSuccessed(res)) {
      apiOptions.value = res.data || []
    }
  })
})
</script>

<template>
  <main class="page-main">
    <a-form
        :model="formData"
        name="basic"
        autocomplete="off"
        :label-col="{ span: 3 }"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
    >
      <a-form-item
          :label="formData.type === 'Menu' ? '菜单名称' : '按钮名称'"
          name="name"
          :rules="rules.name"
      >
        <a-input v-model:value="formData.name" />
      </a-form-item>

      <a-form-item
          v-if="formData.type === 'Menu'"
          label="父级分组"
          name="groupId"
          :rules="rules.groupId"
      >
        <a-select
            v-model:value="formData.groupId"
            :options="groupTree"
            placeholder="请选择分组"
        />
      </a-form-item>

      <a-form-item
          :label="formData.type === 'Menu' ? '前端路径' : '唯一标识'"
          name="webPath"
          :rules="rules.webPath"
      >
        <a-input v-model:value="formData.webPath" />
      </a-form-item>

      <a-form-item label="图标" name="iconName">
        <icon-selector
            :icon-name="formData.iconName"
            @changed="handleIconChanged"
            :key="new Date().getTime()"
        />
      </a-form-item>

      <a-form-item label="API" name="apiSignatureCode">
        <a-select
            show-search
            optionFilterProp="label"
            mode="multiple"
            v-model:value="formData.apiList"
            :options="apiOptions"
        />
      </a-form-item>

      <a-form-item label="排序" name="sort">
        <a-input-number class="width" v-model:value="formData.sort" />
      </a-form-item>

      <a-flex class="width" justify="space-around">
        <a-button type="primary" html-type="submit">提交</a-button>
        <a-button @click="handleClose">取消</a-button>
      </a-flex>
    </a-form>
  </main>
</template>

<style scoped>
/* 可以在这里添加样式 */
</style>
